from flask import g, Flask, url_for, redirect, request, render_template, session
from flask_migrate import Migrate
from exts import db, get_time
from models import File, Classes, User, Student, Teacher, Root, SystemLog
from forms import LoginForm
from flask_login import current_user, LoginManager, login_required
import config
from decorations import teacher_required, root_required, student_required
from my_configs import online_programming_url, weixinpay_url
import requests

from blueprints.user import bp as user_bp
from blueprints.teacher import bp as teacher_bp
from blueprints.student import bp as student_bp
from blueprints.admin import bp as admin_bp
from blueprints.file import bp as file_bp
from blueprints.test_paper import bp as test_paper_bp
from blueprints.classes import bp as classes_bp
from blueprints.question_bank import bp as question_bank_bp
from blueprints.teacher_question_bank_rel import bp as teacher_question_bank_rel_bp
from blueprints.sign_in import bp as sign_in_bp
from blueprints.api.student import bp as api_student_bp

app = Flask(__name__)
app.config.from_object(config)
db.init_app(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login"
login_manager.login_message_category = "warning"

app.register_blueprint(user_bp)
app.register_blueprint(teacher_bp)
app.register_blueprint(student_bp)
app.register_blueprint(admin_bp)
app.register_blueprint(file_bp)
app.register_blueprint(test_paper_bp)
app.register_blueprint(classes_bp)
app.register_blueprint(question_bank_bp)
app.register_blueprint(teacher_question_bank_rel_bp)
app.register_blueprint(sign_in_bp)
app.register_blueprint(api_student_bp)


migrate = Migrate(app, db)


@login_manager.user_loader
def load_user(user_id):
    user = User.query.get(int(user_id))
    return user


# todo before_request
@app.before_request
def before_request():
    sl = SystemLog(
        full_path=request.full_path,
        method=request.method,
        remote_addr="request.headers['X-Real-Ip']",
        user_agent=request.user_agent,
        create_time=get_time(),
        update_time=get_time(),
        is_delete=0
    )
    if current_user.is_authenticated:
        g.user = current_user
        sl.user = current_user
    else:
        g.user = None
        sl.user = db.session.query(User).get(0)

    db.session.add(sl)
    db.session.commit()


# ---------- 在线编程 ---------------
# todo url online_code 在线编程
@app.route("/online_code", methods=["POST"])
@login_required
def online_code():
    code = request.values.get("code")
    result = requests.post(
        url=online_programming_url,
        data={"code": code}
    )
    return result.text


# todo online_programming
@app.route("/online_programming")
@login_required
def online_programming():
    content = {
        "user": g.user,
    }
    return render_template("online_programming.html", **content)


# ---------------------------------
# -------------- 文件 --------------
# todo download 文件
@app.route("/download")
@login_required
def download():
    content = {
        "user": g.user,
        "files": db.session.query(File).all()
    }
    return render_template("download.html", **content)


# todo upload
@app.route("/upload")
@login_required
def upload():
    content = {
        "user": g.user,
    }
    return render_template("upload.html", **content)


# todo index_file
@app.route('/index_file')
@login_required
def index_file():  # put application's code here
    content = {
        "user": g.user,
    }
    return render_template("index_file.html", **content)


# ---------------------------------------------
# todo url / 未登陆主界面
@app.route("/")
def index():
    content = {
        "weixinpay_url": weixinpay_url
    }
    try:
        if g.user.power == 0:
            return redirect("/admin")
        elif g.user.power == 1:
            return redirect("/teacher")
        else:
            return redirect("/student")
    except:
        return render_template("index.html", **content)


# todo url /student 学生登陆主界面
@app.route("/student")
@login_required
@student_required
def student():
    content = {
        "user": g.user,
    }
    return render_template("student/index.html", **content)


# todo url /teacher 教师登陆主界面
@app.route("/teacher")
@login_required
@teacher_required
def teacher():
    content = {
        "user": g.user,
    }
    return render_template("teacher/index.html", **content)


# todo url /admin 管理员登陆主界面
@app.route("/admin")
@login_required
@root_required
def admin():
    content = {
        "user": g.user,
        "xAxis_data": ['学生', '老师', '管理员'],
        "series_data": [len(db.session.query(Student).all()), len(db.session.query(Teacher).all()), len(db.session.query(Root).all())]
    }
    return render_template("admin/index.html", **content)


# todo url /login 登陆界面
@app.route("/login")
def login():
    content = {
    }
    return render_template("login.html", **content)


# # url /register
# @app.route("/register")
# def register():
#     return render_template("register.html")


# @app.route("/test", methods=["GET", "POST"])
# def test():
#     form = LoginForm()
#     if request.method == "POST":
#         print(form.data)
#         return "success"
#     else:
#         content = {
#             "form": form
#         }
#         return render_template("test.html", **content)
#
#
# @app.route("/test_login", methods=["GET", "POST"])
# def test_login():
#     u = current_user.is_authenticated
#     print(u)
#     return "test_login"


@app.route("/test")
def test_login():
    return render_template("test.html")


if __name__ == '__main__':
    app.run(
        host="0.0.0.0",
        port=5002
    )
